package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.concurrent.TimeUnit;

/**
 * 认证状态校验切面类
 * 切面=通知+切入点 将增强功能作用到切入点上
 *
 * @author: atguigu
 * @create: 2024-04-07 11:38
 */
@Slf4j
@Aspect
@Component
public class GuiGuLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 采用环绕通知，对所有模块中controller层方法并且使用@GuiGuLogin注解方法进行增强
     *
     * @param pjp 切入点目标方法对象
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(guiGuLogin)")
    public Object doBasicProfiling(ProceedingJoinPoint pjp, GuiGuLogin guiGuLogin) throws Throwable {
        //一、前置通知逻辑
        log.info("前置通知逻辑..");
        //1. 通过请求上下文获取请求对象
        //1.1 获取RequestAttributes（接口） SpringMVC底层将请求属性对象放入ThreadLocal
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //1.2 RequestAttributes强转为ServletRequestAttributes（实现类）
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = sra.getRequest();

        //2.通过请求对象获取请求头token
        String token = request.getHeader("token");

        //3.查询Redis获取用户信息
        //3.1 构建用户token对应key 登录成功后存入key形式：user:login:token
        String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        //3.2 查询Redis用户信息    登录成功存入Val值：UserInfoVo对象
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(loginKey);

        //3.3 判断目标方法是否要求必须登录 要求登录且用户vo为空抛出异常 业务状态码：208 前端进行登录页面跳转
        if (guiGuLogin.required() && userInfoVo == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }

        //4.将用户ID存入ThreadLocal
        if (userInfoVo != null) {
            //4.1 获取当前用户令牌过期时间
            Long ttlHours = redisTemplate.getExpire(loginKey, TimeUnit.HOURS);
            if (ttlHours <= 12) {
                redisTemplate.expire(loginKey, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
            }
            //4.2 判断过期时间是否小于规定阈值 进行续期
            AuthContextHolder.setUserId(userInfoVo.getId());
        }
        Object retVal;
        try {
            //二、执行目标方法（被增强方法执行）
            retVal = pjp.proceed();
        } finally {
            //三、后置通知逻辑
            log.info("后置通知逻辑..");
            //5.清理ThreadLocal中数据
            AuthContextHolder.removeUserId();
        }
        return retVal;
    }
}
